package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.Permission;
import com.itheima.domain.system.Role;
import com.itheima.domain.system.User;
import com.itheima.utils.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/system/user")
public class UserServlet extends BaseServlet {

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.login(username, password);
        if (user != null) {
            request.getSession().setAttribute("user", user);
            List<Permission> permissionList = userService.findPermissionById(user.getId());
            request.getSession().setAttribute("permissionList", permissionList);

            StringBuffer sbf=new StringBuffer();
            for (Permission p : permissionList) {
                sbf.append(p.getUrl());
                sbf.append(",");
            }
            request.getSession().setAttribute("authorStr",sbf.toString());
            String ck = request.getParameter("ck");
            if ("1".equals(ck)) {
                System.out.println("ck = " + ck);
                Cookie cookie = new Cookie("ck", username + "_" + password);
                cookie.setMaxAge(60 * 60 * 24 * 7);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            request.getRequestDispatcher("/pages/home/main.jsp").forward(request, response);
        } else {
            request.setAttribute("msg", "用户名或密码错误!");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        Cookie cookie = new Cookie("ck", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    public void forgetPwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        if (email != null) {
            boolean flag = userService.findEmail(email);
            if (flag) {
                int i = userService.setPassword(password, email);
                System.out.println("i = " + i);
                if (i > 0) {
                    request.setAttribute("msg", "修改密码成功");
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                }
            } else {
                request.setAttribute("msg1", "请输入正确的邮箱");
                request.getRequestDispatcher("/forgetPwd.jsp").forward(request, response);
            }
        }
    }

    public void updatePwd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String password = request.getParameter("password");
        String newPassword = request.getParameter("newPassword");
        String id = request.getParameter("id");
        if (password.equals(newPassword)) {
            System.out.println("相等");
            userService.updatePassword(password, id);
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } else {
            request.setAttribute("msg", "新密码和确认密码不一致");
            request.getRequestDispatcher("/pages/password/password.jsp").forward(request, response);
        }
    }



    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //进入列表页
        //获取数据
        int page = 1;
        int size = 5;
        if (StringUtils.isNotBlank(request.getParameter("currentPage"))) {
            page = Integer.parseInt(request.getParameter("currentPage"));
        }
        if (StringUtils.isNotBlank(request.getParameter("pageSize"))) {
            size = Integer.parseInt(request.getParameter("pageSize"));
        }
        PageInfo all = userService.findAll(page, size);
        //将数据保存到指定的位置
        request.setAttribute("page", all);
        //跳转页面
        request.getRequestDispatcher("/pages/system/user/user-list.jsp").forward(request, response);
    }

    public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 跳转页面
        request.getRequestDispatcher("/pages/system/user/user-add.jsp").forward(request, response);
    }

    public void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将数据获取到，封装成一个对象
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");
        //调用service
        userService.save(user);
        //跳转list
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    //查看详情
    public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询要查看的数据findById
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        User user = userService.findById(id);
        //将数据加载到指定区域，供页面获取
        request.setAttribute("user", user);
        //跳转页面
        request.getRequestDispatcher("/pages/system/user/user-update.jsp").forward(request, response);
    }

    //查看详情
    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 将获取到的封装成一个对象
        User user = BeanUtil.fillBean(request, User.class);
        // 调用业务层接口update
        userService.update(user);
        // 跳转回到list页面
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将数据获取到，封装成一个对象
        User user = BeanUtil.fillBean(request, User.class);
        //调用业务层接口save
        userService.delete(user);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] ids = request.getParameterValues("ids");
        userService.deleteByIds(ids);
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    public void findByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //进入列表页
        //获取数据
        int page = 1;
        int size = 5;
        if (StringUtils.isNotBlank(request.getParameter("page"))) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (StringUtils.isNotBlank(request.getParameter("size"))) {
            size = Integer.parseInt(request.getParameter("size"));
        }
        String username = request.getParameter("username");
        System.out.println(username);
        PageInfo all = userService.findByName(page, size, username);
        //将数据保存到指定的位置
        request.setAttribute("page", all);
        //跳转页面
        request.getRequestDispatcher("/pages/system/user/user-list.jsp").forward(request, response);
    }

    public void turnStatus(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String id = request.getParameter("id");
        String status = request.getParameter("status");
        userService.turnStatus(id, status);
        request.setAttribute("id", id);
        request.setAttribute("status", status);
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    public void userRole(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uid = request.getParameter("id");
        List<Role> roleList = roleService.findByUid(uid);
        request.setAttribute("roleList", roleList);
        request.setAttribute("id", uid);
        request.getRequestDispatcher("/pages/system/user/user-role-add.jsp").forward(request, response);
    }

    public void addRoleToUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户的id与角色的id数组
        String uid = request.getParameter("id");
        String[] ids = request.getParameterValues("ids");
        /* System.out.println(uid+"----"+ids);*/
        roleService.addRoleToUser(ids, uid);
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }
}
